﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectHopur23.Models;
using ProjectHopur23.Repositories;

namespace ProjectHopur23.Controllers
{
	public class TicTacToeController : Controller
	{
		#region Variables
		private IRepository rep = null;
		#endregion

		#region Constructors
		public TicTacToeController(IRepository r)
		{
			rep = r;
		}

		public TicTacToeController()
		{
			rep = new Repository();
		}
		#endregion

		[Authorize]
		public ActionResult Playing(int? id)
		{
			if(id == null)
			{
				return View("Error");
			}

			GameController gc = new GameController();
			ActiveGame ag = gc.GetActiveGameByID(id.Value);
			if(gc.GameIsValidInstance(ag, "TicTacToe", HttpContext.User.Identity.Name) == false)
			{
				return View("Error");
			}

			GameViewModel ttt = new GameViewModel();
			ttt.listOfPlayers = gc.GetAllUsersInActiveGame(id.Value);
			ttt.theActiveGame = ag;
			ttt.comments = from c in rep.GetAllComments()
					where c.activeGameId == ag.ID
					select c;

			TicTacToeState[] gameStates = (from t in rep.GetAllTicTacToeStates()
											where t.activeGameId == ag.ID
											select t).ToArray();

			if(gameStates.Any() == false)
			{
				gameStates = new TicTacToeState[9];
				for(int i = 0; i < 9; i++)
				{
					gameStates[i] = new TicTacToeState();
					gameStates[i].activeGameId = ttt.theActiveGame.ID;
					gameStates[i].cellId = i;
					gameStates[i].playerId = -1;

					rep.AddTicTacToeState(gameStates[i]);
					rep.Save();
				}
			}

			return View(ttt);
		}
	}
}
